import axios from 'axios'
// MessageBox,
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// import {Base64} from 'js-base64';

const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: 'http://123.60.222.96:8011',
  timeout: 10000000 // request timeout
})

service.interceptors.request.use(
  config => {
    // console.log(store.getters.token, 'store.getters.token')
    // if (store.getters.token) {
    config.headers['X-Token'] = getToken()
    config.headers['Authorization'] = getToken()
    // config.headers['Blade-Auth'] = 'Bearer ' + getToken()
    // config.headers['Authorization'] = 'JWT ' + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo5LCJ1c2VybmFtZSI6IjEzOTk0MDI2NDc1IiwiZXhwIjoxNjI0NjM4OTA5LCJlbWFpbCI6IiIsIm9yaWdfaWF0IjoxNjI0MDM0MTA5fQ.1hWjLrFjbn2Dn9xNC7IbDckCnMR4ohzasj9N4MD_LGg'
    // config.headers['Blade-Auth'] = 'bearer ' + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo5LCJ1c2VybmFtZSI6IjEzOTk0MDI2NDc1IiwiZXhwIjoxNjI0NjM4OTA5LCJlbWFpbCI6IiIsIm9yaWdfaWF0IjoxNjI0MDM0MTA5fQ.1hWjLrFjbn2Dn9xNC7IbDckCnMR4ohzasj9N4MD_LGg'
    // }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    console.log(response)
    const res = response.data
    // console.log(response, 'res')
    // console.log(res, 'res')
    // if (!(response.status === 200 || response.status === 201 || response.status === 202 || response.status === 203 || response.status === 204)) {
    if (!(response.data.code === 200 || response.data.code === 201 || response.data.code === 202 || response.data.code === 203 || response.data.code === 204)) {
      // if ((response.config.muted !== undefined) && !response.config.muted) {
      if (!response.config.muted) {
        Message({
          message: res.msg || '错误',
          type: 'error',
          duration: 3e3
        })
      }

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      // if (response.status === 500 || response.status === 401 || response.status === 404 || response.status === 403) {
      // response.data.code === 500 || response.data.code === 401 || response.data.code === 404 ||
      if (response.data.code === 403) {
        // to re-login
        // MessageBox.confirm('登录过期，请重新登陆', '警告', {
        //   confirmButtonText: '重新登陆',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        // })
        // console.log('token无效')
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      if (res.code && +res.code !== 200) {
        if (!response.config.muted) {
          Message({
            message: res.msg || '错误',
            type: 'error',
            duration: 3e3
          })
        }
        return Promise.reject(res)
      }
      if (Object.keys(response.headers).includes('correlation-id')) {
        res.data && (res.data.uuid = response.headers['correlation-id'])
      }
      return res
    }
  },
  error => {
    // const status = error.response.status
    const code = error.response.data.code
    // if (status === 401) {
    if (code === 401) {
      Message({
        message: '请求未授权',
        type: 'error',
        duration: 3 * 1000
      })
    } else if (error && error.response && error.response.data && error.response.data.error) {
      console.log('err' + error) // for debug
      Message({
        message: error.response.data.error.message,
        type: 'error',
        duration: 3 * 1000
      })
    } else {
      console.log('err' + error) // for debug
      Message({
        message: error.response.data.message || '服务器异常',
        type: 'error',
        duration: 3 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
